import asyncio
import json
import websockets
# 代码完全开源；额外服务：1对1讲解js逆向讲解，远程操作；视频讲解;【技术付费】。
# 威信：crazy20010110
# 技术采用websocket技术，可以获取消息有用户关注、用户点赞、用户进入直播间、用户发言、用户刷礼物以及用户个人信息。支持任何可以创建服务器的语言

async def check_permit(websocket):
    """

    :param websocket: 服务器发送给客户端
    :return: True
    """
    send_text = 'Successful connection to the server'
    await websocket.send(send_text)
    return True


async def recv_msg(websocket):
    """

    :param websocket: 接受服务器发送的消息
    :return:
    """
    while True:
        recv_text = await websocket.recv()
        try:
            data = json.loads(recv_text)
            type = data['type']
            cursor = db.cursor()
            username = data['username']
            gender = data['gender']
            if gender == 0:
                gender = '女'
            elif gender == 1:
                gender = '男'
            else:
                gender = '未知'
            followingCount = data['followingCount']
            followerCount = data['followerCount']
            level = data['level']
            head_img = data['head_img']
            uid = data['uid']
            print(data)
            # 用户评论内容
            if type == "WebcastChatMessage":
                context = data['context']
                # 插入数据库
                sql = 'INSERT INTO `chat`(`username`, `content`, `gender`,`followingCount`, `followerCount`,`level`, ' \
                      '`head_img`, ' \
                      '`uid`)VALUES (\'{0:}\',\'{1:}\',\'{2:}\',\'{3:}\',\'{4:}\',\'{5:}\',\'{6:}\',\'{7:}\')'.format(
                    username, context, gender, followingCount, followerCount, level,
                    head_img, uid)

                # 执行sql语句
                cursor.execute(sql)
                # 提交到数据库执行
                db.commit()
            # 进入直播间
            elif type == "WebcastMemberMessage":
                memberCount = data['memberCount']
                sql = 'INSERT INTO `member`(`username`, `memberCount`,`gender`,`followingCount`, `followerCount`,' \
                      '`level`, ' \
                      '`head_img`, ' \
                      '`uid`)VALUES (\'{0:}\',\'{1:}\',\'{2:}\',\'{3:}\',\'{4:}\',\'{5:}\',\'{6:}\',\'{7:}\')'.format(
                    username, memberCount, gender, followingCount, followerCount, level, head_img, uid)
                # 执行sql语句
                cursor.execute(sql)
                # 提交到数据库执行
                db.commit()
            #  点赞/总的点赞量
            elif type == "WebcastLikeMessage":
                count = data['count']
                total = data['total']
                sql = 'INSERT INTO `like`(`username`, `count`,`total`,`head_img`, `uid`)VALUES (\'{0:}\',\'{1:}\',' \
                      '\'{2:}\',\'{3:}\',\'{4:}\')'.format(username, count, total, head_img, uid)
                # 执行sql语句
                cursor.execute(sql)
                # 提交到数据库执行
                db.commit()
            #  礼物
            elif type == "WebcastGiftMessage":
                describe = data['describe']
                sql = 'INSERT INTO `gift`(`username`, `describe`,`head_img`, `uid`)VALUES (\'{0:}\',\'{1:}\',' \
                      '\'{2:}\',\'{3:}\')'.format(username, describe, head_img, uid)
                # 执行sql语句
                cursor.execute(sql)

        except:

            # Rollback in case there is any error
            db.rollback()


async def main_logic(websocket):
    await check_permit(websocket)
    await recv_msg(websocket)
# 代码完全开源；额外服务：1对1讲解js逆向讲解，远程操作；视频讲解;【技术付费】。
# 威信：crazy20010110
# 技术采用websocket技术，可以获取消息有用户关注、用户点赞、用户进入直播间、用户发言、用户刷礼物以及用户个人信息。支持任何可以创建服务器的语言

import MySQLdb

try:
    # 连接mysql数据库
    db = MySQLdb.connect("localhost", "root", "123456", "douyin", charset='utf8mb4')
    cursor = db.cursor()
    # 数据库创建chart、gift、like、member表
    sql = '''DROP TABLE IF EXISTS `chat`;
                CREATE TABLE `chat`(`username` VARCHAR(255),
                `content` VARCHAR(255),
                `gender` VARCHAR(255),
                `followingCount` VARCHAR(255),
                `followerCount` VARCHAR(255),
                `level` VARCHAR(255),
                `uid` VARCHAR(255),
                `head_img` VARCHAR(255));
                DROP TABLE IF EXISTS `member`;
                CREATE TABLE `member`(`username` VARCHAR(255),
                `memberCount` VARCHAR(255),
                `gender` VARCHAR(255),
                `followingCount` VARCHAR(255),
                `followerCount` VARCHAR(255),
                `level` VARCHAR(255),
                `uid` VARCHAR(255),
                `head_img` VARCHAR(255));
                DROP TABLE IF EXISTS `like`;
                CREATE TABLE `like`(`username` VARCHAR(255),
                `count` VARCHAR(255),
                `total` VARCHAR(255),
                `uid` VARCHAR(255),
                `head_img` VARCHAR(255));
                DROP TABLE IF EXISTS `gift`;
                CREATE TABLE `gift`(`username` VARCHAR(255),
                `describe` VARCHAR(255),
                `uid` VARCHAR(255),
                `head_img` VARCHAR(255));
                
                '''
    cursor.execute(sql)

    print('数据库创建chart、gift、like、member表成功')
except:
    pass

start_server = websockets.serve(main_logic, '127.0.0.1', 9999)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
